package com.youyun56.gps.android.pool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.youyun56.gps.android.GpsActivity;
import com.youyun56.gps.android.GpsFactory;
import com.youyun56.gps.android.MainTabActivity;
import com.youyun56.gps.android.RunStep;
import com.youyun56.gps.android.commands.CommandType;
import com.youyun56.gps.android.common.JSONKey;
import com.youyun56.gps.android.dao.ImDao;
import com.youyun56.gps.android.pojo.Car;
import com.youyun56.gps.android.pojo.Im;
import com.youyun56.gps.android.service.LocationUploadService;

public class MessageHander extends Handler {
    private final static String tag = MessageHander.class.getName();
    private GpsActivity activity;
    private ProgressDialog pBar;
    private File downFile = new File(Environment.getExternalStorageDirectory(), "youyun.apk");

    public MessageHander(GpsActivity activity, Looper looper) {
        super(looper);
        this.activity = activity;
    }

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        final JSONObject input = (JSONObject) msg.obj;
        switch (msg.what) {
        case CommandType.Login:
            try {
                Boolean success = input.getBoolean("success");
                if (success) {
                    LocationUploadService service = activity.getService();
                    Car car = new Car();
                    if (!input.isNull("CAR")) {
                        JSONObject carO = input.getJSONObject("CAR");
                        car.setId(carO.getLong("id"));
                        car.setCarId(carO.getString("carId"));
                        car.setPartner(carO.getInt("partner"));
                        car.setCarMobile(carO.getString("carMobile"));
                        car.setPwd(carO.getString("pwd"));
                        car.setProvince(carO.getInt("province"));
                        car.setCityId(carO.getInt("cityId"));
                        car.setLastPositionTime(carO.getString("lastPositionTime"));
                        car.setCarryStatus(carO.getString("carryStatus"));
                        car.setPosition(carO.getString("position"));
                        car.setFocusCity(car.getCityId());
                        car.setProvince(13);
                        car.setCityId(124);
                        service.setCar(car);
                        service.getPreference().edit().putLong("id", car.getId()).commit();
                    }
                    if (service.getCar().getPartner() == LocationUploadService.gpsUpload) {

                        if (!service.startGps(input.getLong("gpsinterval"))) {
                            activity.getPd().dismiss();
                            new AlertDialog.Builder(activity).setTitle("提示").setMessage("手机不支持定位，请打开GPS设备")// 设置内容
                                    .setPositiveButton("确定",// 设置确定按钮
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    activity.startActivity(new Intent(
                                                            "android.settings.LOCATION_SOURCE_SETTINGS"));

                                                }

                                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            // 点击"取消"按钮之后退出程序
                                            dialog.dismiss();
                                        }
                                    }).create().show();
                        }
                    } else {
                        GpsFactory.factory.stop();
                    }
                    Intent intent = new Intent();
                    intent.setClass(activity, MainTabActivity.class);
                    activity.startActivity(intent);
                    if (!input.isNull(JSONKey.IMS)) {
                        List<Im> ims = service.getIms();
                        JSONArray array = input.getJSONArray(JSONKey.IMS);
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject o = array.getJSONObject(i);
                            Im im = new Im();
                            im.setAddDay(o.getString("addDay"));
                            im.setAttach(o.getString("attach"));
                            im.setContext(o.getString("context"));
                            im.setUserId(o.getLong("userId"));
                            ims.add(im);
                            ImDao.getInstance().saveIm(im);
                        }
                    }
                    service.setRunStep(RunStep.MAIN);
                    activity.getPd().dismiss();
                    activity.finish();
                } else {
                    String error = input.getString("msgs");
                    if (input.has("version")) {
                        activity.getPd().dismiss();
                        new AlertDialog.Builder(activity).setTitle("系统更新").setMessage(error)// 设置内容
                                .setPositiveButton("确定",// 设置确定按钮
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                pBar = new ProgressDialog(activity);
                                                pBar.setTitle("正在下载");
                                                pBar.setMessage("请稍候...");
                                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                                try {
                                                    downFile(String.format(
                                                            "http://1683333.com/downfiles/youyun56%s.apk",
                                                            input.getString("version")));
                                                } catch (JSONException e) {
                                                    Log.e(tag, e.getMessage(), e);
                                                }

                                            }

                                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        // 点击"取消"按钮之后退出程序
                                        dialog.dismiss();
                                    }
                                }).create().show();
                    } else if (input.has("imis")) {
                        activity.getPd().dismiss();
                        new AlertDialog.Builder(activity).setTitle("错误序列号").setMessage(error).setNeutralButton("确定",// 设置确定按钮
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }

                                }).create().show();
                    } else {
                        activity.getPd().dismiss();
                        new AlertDialog.Builder(activity).setTitle("错误").setMessage(new StringBuffer(error))
                                .setNeutralButton("确定",// 设置确定按钮
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }

                                        }).create().show();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                Log.e(tag, e.getMessage(), e);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e(tag, e.getMessage(), e);
            }
            break;
        }
    }

    void downFile(final String url) {
        pBar.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                // params[0]代表连接的url
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {

                        fileOutputStream = new FileOutputStream(downFile);

                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            // baos.write(buf, 0, ch);
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) {

                            }

                        }

                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down();
                } catch (Exception e) {
                    Log.e(tag, e.getMessage(), e);
                }
            }

        }.start();

    }

    void down() {
        this.post(new Runnable() {
            public void run() {
                pBar.cancel();
                update();
            }
        });

    }

    void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(downFile), "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }
}
